package io.plus.user_interface.redis;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class CacheManager {

    private static Map<String, CacheImpl> cacheNameToCacheMap = new HashMap<>();

    public static CacheImpl getCache(String cacheName) {
        CacheImpl cacheImpl = cacheNameToCacheMap.get(cacheName);
        return cacheImpl;
    }

    /**
     * timeToLiveSeconds和timeToIdleSeconds不允许同时为null
     */
    public static CacheImpl register(String cacheName, Integer timeToLiveSeconds, Integer timeToIdleSeconds) {
        ExpireTask.start();

        CacheImpl cacheImpl = cacheNameToCacheMap.get(cacheName);
        if (cacheImpl == null) {
            synchronized (CacheManager.class) {
                cacheImpl = cacheNameToCacheMap.get(cacheName);
                if (cacheImpl == null) {
                    cacheImpl = new CacheImpl(cacheName, timeToLiveSeconds, timeToIdleSeconds);
                    cacheNameToCacheMap.put(cacheName, cacheImpl);
                }
            }
        }
        return cacheImpl;
    }


}
